﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace OmniKits.Windows.Converters
{
    public class TimeSpanStringifyConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;

            if (value is string)
                return ConvertBack(value, targetType, parameter, culture);

            return ((TimeSpan)value).ToString("g");
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;

            if (value is TimeSpan)
                return Convert(value, targetType, parameter, culture);

            var s = (string)value;
            var sa = s.Split(':');

            try
            {
                switch (sa.Length)
                {
                    case 1:
                        return TimeSpan.FromSeconds(double.Parse(s));
                    case 2:
                        var minutes = double.Parse(sa[0]);
                        var seconds = double.Parse(sa[1]);
                        if (seconds < 0 || seconds >= 60)
                            throw new FormatException();
                        if (minutes < 0)
                            seconds = -seconds;
                        return TimeSpan.FromMinutes(minutes) + TimeSpan.FromSeconds(seconds);
                    case 3:
                        return TimeSpan.Parse(s);
                    default:
                        throw new FormatException();
                }
            }
            catch
            {
                return DependencyProperty.UnsetValue;
            }
        }
    }
}
